<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');

class Images_mod extends CI_Model
{   
    
    private $_dbTableUserImages = 'images';
    /**
     *  class sonstructor
     */
    function __construct() 
	{
		// Call the Model constructor
        parent::__construct();
	}
    
    
    public function getUserImages($id,$like_array = true)
    {
        $this->db->select('*');
      
        $this->db->where('user_id',$id);

        $query = $this->db->get($this->_dbTableUserImages);                         

        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {
          if($like_array) 
            $images = $query->result_array(); // Return ARRAY
          else
            $images = $query->result(); 

          $query->free_result();
        } else {
          $images = NULL;
        }

        return $images;
    }
    
    
    public function getMainImage($user_id)
    {
        $query = $this->db->select('name')
                          ->where('user_id',$user_id) // Za tog user-a
                          ->where('private',0) // Nije privatna (nije locked)
                          ->order_by('main','DESC') // Prvo da ide main=1
                          ->get($this->_dbTableUserImages);
        
         $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() > 0) {         
          $image_name = $query->row()->name; // Return image name
          $query->free_result();
        } else {
          $image_name = NULL;
        }
        
        return $image_name;
        
    }
    
    public function getUserId($image_id)
    {
        $this->db->select('user_id')
                 ->from($this->_dbTableUserImages)
                 ->where('id',$image_id);
        $query = $this->db->get();
        
        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }

        if ($query->num_rows() == 1) {
          $result = $query->row()->user_id;
          $query->free_result();
        } else {
          $result = NULL;
        }

        return $result;
    }
    
    public function insertImage($user_id,$file_name)
    {
        $data = array( 'user_id'=>$user_id, 'name'=>$file_name,'private'=>0 );
        $this->db->insert($this->_dbTableUserImages,$data);
        
        //echo $this->db->last_query();
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
          throw new Exception("SQL Error: " . $errors);
        } else { }
    }
    
    
    public function lock_unlock_img($id) 
    {
        $sql = "UPDATE {$this->_dbTableUserImages} SET `private` = (`private` + 1) MOD 2 WHERE `id` = {$id};";
        
        $query = $this->db->query($sql);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
            throw new Exception("SQL Error: " . $errors);
        } else { }
        
        if ($this->db->affected_rows() == 1)
            return true; // Uspesno upisano
        else
            return false; // Nesuspesan upis
    }
    
    public function set_profile_img($id)
    {
        // Prvo postavi svuda main=0 za tog usera
        $user_id = $this->getUserId($id);
        $data = array('main'=>0);
        //$sql = "UPDATE {$this->_dbTableUserImages} SET `main`=0 WHERE `user_id` = {$id};";
        //$query = $this->db->query($sql);
        $query = $this->db->where('user_id',$user_id)->update($this->_dbTableUserImages,$data);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
            throw new Exception("SQL Error: " . $errors);
        } else { }
        
        
        // postavi main samo za tu sliku
        $data = array('main'=>1);
        $query = $this->db->where('id',$id)->update($this->_dbTableUserImages,$data);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
            throw new Exception("SQL Error: " . $errors);
        } else { }
        
        if ($this->db->affected_rows() == 1)
        {
            // Postavi ime odabrane slike u sesiju.
            $this->_setSessMainImg($id);
            return true; // Uspesno upisano
        }
        else
            return false; // Nesuspesan upis
    }
    
    private function _setSessMainImg($id)
    {
        $query = $this->db->select('name')
                          ->where('id',$id)
                          ->get($this->_dbTableUserImages);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
            throw new Exception("SQL Error: " . $errors);
        } else { }
        
         if ($query->num_rows() == 1) {
          $result = $query->row()->name;
          $this->session->set_userdata('main_img',$result);
          $query->free_result();
        } else {
          $result = NULL;
        }
    }


    public function delete_img($id)
    {
        $image = $this->_getImageData($id);
        
        $image_dir = $this->config->item('image_path').$image->user_id.'/'; // .../images/ID/
        
        // Delete image file's
        $file = $image_dir."big/".$image->name;
        if(file_exists($file) )
          unlink( $file );
        
        $file = $image_dir."small/".$image->name;
        if(file_exists($file) )
          unlink( $file );
        
        $file = $image_dir."thumb/".$image->name;
        if(file_exists($file) )
          unlink( $file );
        
        $file = $image_dir . $image->name;
        if(file_exists($file) )
          unlink( $file );
        
        $this->db->delete($this->_dbTableUserImages, array('id' => $id)); 
        
         $errors = $this->db->_error_message();
        if (!empty($errors)) {
            throw new Exception("SQL Error: " . $errors);
        } else { }
        
        if ($this->db->affected_rows() == 1)
            return true; // Uspesno obrisano
        else
            return false; // Nesuspesno brisanje
    }
     
    
    
    private function _getImageData($id)
    {
      $query = $this->db->select('*')->where('id',$id)->get($this->_dbTableUserImages);
        
        $errors = $this->db->_error_message();
        if (!empty($errors)) {
            throw new Exception("SQL Error: " . $errors);
        } else { }
        
        if ($query->num_rows() == 1) {
          $result = $query->row();
          $query->free_result();
        } else {
          $result = NULL;
        }
        
        return $result;
    }
    
}// end class Images_mod

/*
      $query = $this->db->select('*')
                        ->from()
                        ->where()
                        ->get();
      //echo $this->db->last_query();
      $errors = $this->db->_error_message();
      if (!empty($errors)) {
        throw new Exception("SQL Error: " . $errors);
      } else { }

      if ($query->num_rows() > 0) {
        $result = $query->result();
        $query->free_result();
      } else {
        $result = NULL;
      }

      return $result;
 */

// end file: application/models/images_mod.php

?>